import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
import { store } from '@/store';
import { MenuTree, MenuTreeVue } from '@/api/user/types';
import { tree } from '@/utils/utils'

const modules = import.meta.glob('../../views/**/**.vue');
const Layout = () => import('@/layout/index.vue');

// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  //  遍历后台传来的路由字符串，转换为组件对象
  function filterAsyncRouter(asyncRouterMap: any) {
    console.log('asyncRouterMap++++++', asyncRouterMap)
    const accessedRouters = asyncRouterMap.filter((router: any) => {
      if (router.component) {
        const component = router.component
        if (router.component === 'Layout') { // Layout组件特殊处理
          router.component = Layout
        } else {
          router.component = modules[`../../views/${component}.vue`];
        }
      }
      router.meta ? '' : router.meta = {}
      router.vueIcon ? '' : router.meta.vueIcon = router.vueIcon
      if (router.status === -1) {
        router.meta.hidden = true
      } else if (router.status === 1) {
        router.meta.hidden = false
      }

      if (router.children && router.children.length) {
        router.children = filterAsyncRouter(router.children)
      }
      return true
    })
    // console.log(accessedRouters, 555555)
    return accessedRouters
  }

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    // console.log(newRoutes)
    routes.value = constantRoutes.concat(newRoutes);
    // console.log('routes.value', routes.value)
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(menuTreeVue: MenuTreeVue[]) {
    let list = tree(menuTreeVue, 0, 'parentId')
    list = filterAsyncRouter(list)
    return list
  }
  return { routes, setRoutes, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
